const path = require("path");
const resolve = dir => path.resolve(__dirname, dir);
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const webpack = require('webpack')

module.exports = {
  css: {
    loaderOptions: {
      less: {
        javascriptEnabled: true
      }
    }
  },
   configureWebpack: config => {
    config.resolve.extensions = ['.js', '.ts', '.vue', '.json', '.css']
    // 打包大小分析
    console.log(process.env.NODE_ENV)
    if (process.env.NODE_ENV === 'production') {
      config.plugins.push(new BundleAnalyzerPlugin(
        {
           analyzerMode: 'server',
           analyzerHost: '127.0.0.1',
           analyzerPort: 8889,
           reportFilename: 'report.html',
           defaultSizes: 'parsed',
           openAnalyzer: true,
           generateStatsFile: false,
           statsFilename: 'stats.json',
           statsOptions: null,
           logLevel: 'info'
        }
      ))
    }
    // ant-design-vue中moment包大小优化
    config.plugins.push(new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn/))
  },
  chainWebpack: (config) => {   
    config
      .plugin('html')
      .tap(args => {
        args[0].title= 'VUE3+QIANKUN主应用'
        return args
      });

    // 添加别名
    config.resolve.alias
      .set('@', resolve('./src'))
      .set('lib', resolve('./src/common-lib'))
      .set('lib-utils', resolve('./src/common-lib/utils'))
      .set('lib-comp', resolve('./src/common-lib/components'))
      .set('lib-plugins', resolve('./src/common-lib/plugins'))
      .set('lib-styles', resolve('./src/common-lib/styles'))
      .set('lib-assets', resolve('./src/common-lib/assets'));

    const types = ["vue-modules", "vue", "normal-modules", "normal"];
    types.forEach((type) =>
      addStyleResource(config.module.rule("less").oneOf(type))
    );

    // 分割代码 minSize： 30000表示大于30kb才分割
    config.optimization.splitChunks({
      cacheGroups: {
        vendor: {
          name: 'vendor',
          test: /[\\/]node_modules[\\/]/,
          minSize: 0,
          minChunks: 2,
          priority: 10,
          chunks: 'all'
        },
        echarts: {
          name: 'echarts',
          test(module, chunks) {
            if (/echarts/.test(module.context)) {
              return true;
            }
            return false;
          },
          minSize: 0,
          minChunks: 1,
          priority: 20,
          chunks: 'all'
        }
      }
    });
  }
};

/**
 * 引入全局less变量
 * @param rule
 */
function addStyleResource(rule) {
  rule
    .use("style-resource")
    .loader("style-resources-loader")
    .options({
      patterns: [
        path.resolve(__dirname, "./src/common-lib/styles/variable.less"),
      ],
    });
}
